
var Mod_masonry=function(options){
    this.opts= $.extend({
        sp:1,
        path: ["/V3/assets/js/widgets/test.json?data=",""],
        containor:".infinite_scroll",
        columnWidth:232,
        baseWidth:230,
        distance:150,
        maxCount:9999,
        itemSelector: ".water",
        autoAlign:true,
        firstQuery:false,
        dataType:3,
        isRand:false,
        maxArtId:"",
        pageOrNum:"page",
        state:{
            currNum:0
        }
    },options);
}
Mod_masonry.prototype={
    setMasonry:function(){
        var opts=this.opts;
        var param=$.extend({
            itemSelector: '.water',
            columnWidth:232,
            gutterWidth:15
        },opts);
      $(opts.containor).masonry(param);
    },
    reachBottom:function () {
        var opts=this.opts;
        var scrollTop = 0;
        var clientHeight = 0;
        var scrollHeight = 0;
        var de=document.documentElement,db=document.body;
        //window级别的
        if (de && de.scrollTop) {
            scrollTop = de.scrollTop;
        } else if (db) {
            scrollTop = db.scrollTop;
        }
        if (db.clientHeight && de.clientHeight) {
            clientHeight = (db.clientHeight < de.clientHeight) ? db.clientHeight : de.clientHeight;
        } else {
            clientHeight = (db.clientHeight > de.clientHeight) ? db.clientHeight : de.clientHeight;
        }
        scrollHeight = Math.max(db.scrollHeight, de.scrollHeight);
        //启用不需到底部即开始查询数据
        if (scrollTop + clientHeight >= (scrollHeight-opts.distance)) {
            return true;
        } else {
            return false;
        }
    },
    getTpl:function(data){
        var tpl="";
        var opts=this.opts;
        if(data.length==0){
            opts.isOver=true;
            return;
        }
        $.each(data,function(index,item){
            var imgType,typeHtmlTpl="",comments="",editBar="",baseHeight,baseWidth=opts.baseWidth,longClass="",shadowStop="";
            if(item.width<baseWidth){
                baseWidth=item.width;
                baseHeight=item.height;
            }else{
                baseHeight=Math.round((baseWidth/item.width)*item.height);
            }
            if(baseHeight>=750){
                longClass="long_img";
                shadowStop="<span class='stop_shadow'></span>";
                baseHeight='100%';
            };
            if(item.isRand == "true")
            {
                opts.isRand = "true";
            }
            if(opts.state.currNum == "0")
            {
                $("#maxArtId").val(item.maxArticleId);
            }
            
            if(item.gallery){
                typeHtmlTpl="<ul class='thumblist'>";
                $.each(item.gallery,function(secIndex,secItem){
                    typeHtmlTpl+="<li><img src='"+secItem.thumbPic+"' width='"+secItem.thumbWidth+"' height='"+secItem.thumbHeight+"' /></li>";
                });
                typeHtmlTpl+="</ul>";
            }
           
            if(item.edit){
                editBar='<div class="editbox">';
                
                // 文章是否可移动至活动或专辑
                if(item.mobile)
                {
                	editBar = editBar + '<ul class="mod_drop mod_drop_group hidden">'+
                            '<li><a href="/dialog/moveToGroup/mod_dialog_special/' + item.id + '/" data-width="365" data-toggle="modal" data-target="#mod_dialog_move" data-destory-inner="true">专辑</a></li>'+
                            '<li><a href="/dialog/moveToGroup/mod_dialog_act/' + item.id + '/" data-width="365" data-toggle="modal" data-target="#mod_dialog_move" data-destory-inner="true" class="no_border">活动</a></li>'+
                        '</ul>'+
                    '<a href="javascript:;" class="btn a-btn-light" rel="move" id = "article_mobile_' + item.id + '">移动至<i class="arrow-down-gray"></i>' +
                    '</a>';
                };
                
                // 文章是否可编辑
                if(item.editStatus)
                {
                    editBar = editBar + '<a href="' + item.editUrl + '" class="btn a-btn-light" data-width="620" data-toggle="modal" data-target="#mod_dialog_edit_release" data-destory-inner="true">编辑</a>';
                }
                
                // 文章是否可删除
                if(item.del){
                    editBar = editBar + '<a href="javascript:;" class="btn a-btn-light no_mar" rel="del" data-del-url="' + item.delUrl + '">删除</a>';
                }
                editBar = editBar + '</div>';
            }
            //是动态活动模块. 或者是专辑模块
            if(opts.dataType == 2 || opts.dataType == 1){
                var itemTimer="";
                if(item.timer){
                    itemTimer= '<li><i class="icon icon-timer"></i>'+item.timer+'</li>';
                }

                tpl+='<div class="act_water" data-new="true">'+
                        '<div class="act_bd water_pos">'+
                                    '<div class="water_bd"> '+
                                        '<a class="thumb water_pos show '+longClass+'" target="_blank" href="'+item.url+'">'+
                                         '<img id="I_article_img_' + item.id + '" src="'+item.preview+'_3" title="'+item.title+'"  width="230" height="170" /> '+
                                            shadowStop+
                                            '<span class="opactiy"></span>'+
                                            '<span class="num">'+item.counts+'</span>'+
                                        '</a>'+
                                        '<div class="topbox">'+
                                            '<a target="_blank" class="title" title="'+item.title+'" id="I_article_title_' + item.id + '" target="_blank" href="'+item.url+'">';
                                        if(item.title.length > 18)
                                        {
                                        	tpl+=item.title.substring(0, 17)+'...';
                                        }
                                        else
                                        {
                                        	tpl+=item.title;
                                        }
                                        tpl+='</a>'+
                                        '</div>'+
                                        '<ul class="act_info">'+
                                        '<li class="clearfix"><i class="icon icon-woman"></i>';
                                         if(item.articleIsHidden == 0)
                                         		tpl+='<a href="/show/user_detail/'+item.userHashId+'" target="_blank" class="l fixed w_100" title="'+item.userName+'">'+item.userName+'</a>';
                                         else
                                         {
                                         		tpl+='匿名';
                                         }
                                        tpl+='</li>';
                                        if(opts.dataType == 2)
                                            tpl+='<li><i class="icon icon-timer"></i>'+item.timer+'</li>';
                                        
                                        tpl+='</ul>'+editBar+
                                        '<p class="sharebox">';
                                        
                                        if(opts.dataType == 1)
                                        {
                                        	var attContent = "关注"
													                if(item.isAttention=="true"){
													                  var attContent="取消关注";
													                }
                                            tpl+='<a class="btn btn-red" href="javascript:;"  rel="attention" data-is-attention="'+item.isAttention+'" data-attention-url="'+item.attentionUrl+'"">'+attContent+'</a>';
                                        }
                                        else
                                        {
                                        	  tpl+='<a class="btn btn-red" href="'+item.url+'" data-id="'+item.id+'">参 加</a>';
                                        }
                                        tpl+='</p>'+
                                    '</div>'+
                        '</div>'+
                       '<p class="act_ft sp">&nbsp;</p>'+
                    '</div>'
            }else{
            	
            	  //是否有评论模块
		            if(item.comments){
		                comments='<ul class="media-list list-media-water">';
		                $.each(item.comments.users,function(secIndex,secItem){
		                            comments+=  '<li class="media">'+
		                                        '<a href="'+secItem.userProfileUrl+'" target="_blank" class="pull-left img-rounded-small">'+
		                                         '<img width="30" height="30" src="';
		                                         
		                                         if(secItem.userSmallHead != null && secItem.userSmallHead != '')
		                                         {
		                                         		comments+=secItem.userSmallHead+'_1';
		                                         }
		                                         else
		                                         {
		                                         		comments+='http://static.aceona.com/V3/assets/img/head_30.jpg';
		                                         }
		                                         
		                                         comments+='" class="media-object">'+
		                                        '</a>'+
		                                        '<div class="media-body">'+
		                                        '<a class="a_red_light" target="_blank" href="'+secItem.userProfileUrl+'">'+secItem.userName+'</a>：'+
		                                        '<span>'+secItem.userContent+'</span>'+
		                                        '</div>'+
		                                        '</li>';
		                            });
		                comments+= '</ul>';
		            }
            	  
                var starCurrent="",supportCurrent="";
                
                if (item.support)
                {
                	if(item.support.isCollect=="true"){
                    starCurrent="a-collect-current";
	                }else{
	                    starCurrent="a-collect";
	                }
	                //support
	                if(item.support.isSupport=="true"){
	                    supportCurrent="a-support-current";
	                }else{
	                    supportCurrent="a-support";
	                }
	                //默认的tpl html模块
	                tpl+='<div class="water" data-new="true">'+
	                    '<div class="water_bd">';
	                    
	                    if(item.isShowLogin!=null && item.isShowLogin == '0')
	                    	tpl+='<a href="'+item.imgUrl+'" class="thumb '+longClass+'" data-user-id='+item.id+' data-user-id='+item.userId+' data-toggle="modal" data-target="#modal" data-width="940">';
	                    else
	                    	tpl+='<a href="'+item.imgUrl+'" class="thumb '+longClass+'" target="_blank">';
	                    
	                    tpl+='<img id="I_article_img_' + item.id + '" src="'+item.preview+'_4" title="'+item.title+'" width='+baseWidth+' height='+baseHeight+' />'+ shadowStop+'</a>'+
	                    '<div class="topbox">'+
	                    '<a class="title" title="'+item.title+'" id="I_article_title_' + item.id + '" target="_blank" href="'+item.url+'">';
                      if(item.title.length > 18)
                      {
                      	tpl+=item.title.substring(0, 17)+'...';
                      }
                      else
                      {
                      	tpl+=item.title;
                      }
                      tpl+='</a>'+
	                    '<div class="operate">'+
	                    '<a href="javascript:;" class="'+supportCurrent+'" data-is-support='+item.support.isSupport+' data-support-url="'+item.support.supportUrl+'" rel="support"><i class="icon"></i><span class="num">'+item.support.good+'</span></a>'+
	                    '<a href="'+item.url+'" class="a-comment" target="_blank"><i class="icon icon-comment"></i>'+item.support.commentNumber+'</a>'+
	                    '<a class="'+starCurrent+'" href="javascript:;" data-is-collect='+item.support.isCollect+' rel="collect" data-collect-url="'+item.support.collectUrl+'"><i class="icon icon-star"></i><span class="text_bd">';
	                    if(item.support.isCollect == 'true')
	                    {
	                    		tpl+='已';
	                    }
	                    tpl+='收藏</span></a>'+
	                    '</div>'+
	                    '</div>'+ comments+editBar+
	                    '</div>'+
	                    '</div>';
                }
                
            }
            if(opts.pageOrNum == "num")
            	opts.state.currNum++;
        });
        if(opts.pageOrNum == "page")
            	opts.state.currNum++;
        //加一条记录
        return tpl;
    },
    support:function(){
    	 var opts=this.opts;
    	 
    	 
    	 var supportFlag = true;
       $(document).off("click.waterwall","a[rel='support']").on("click.waterwall","a[rel='support']",function(e){
       		 var url=$(this).attr("data-support-url");           
           var $_self=$(this),$_num=$_self.find("span");
           var $_oldNum = $_num.text();
           var isResult=Ace.chkIsLogin(this,e);
           if(isResult==false){
           	  return false;
          }
          if(supportFlag)
          {
          	 supportFlag = false;
          	 $.getJSON(url,function(data){
                if(data.success){
                    //设值　
                    $_self.find("span").text(parseInt($_oldNum) + parseInt(data.num));
                    if($_self.hasClass("a-support-current")){
                        $_self.removeClass("a-support-current").addClass("a-support");
                        $_self.attr("data-is-support",false);
                        $_self.attr("data-support-url",$_self.attr("data-support-url").replace('/-1/','/1/'));
                    }else{
                        $_self.removeClass("a-support").addClass("a-support-current");
                        $_self.attr("data-is-support",true);
                        $_self.attr("data-support-url",$_self.attr("data-support-url").replace('/1/','/-1/'));
                    }
                    supportFlag = true;
                }
           });
          }
          
       });
       
       var collectFlag = true;
        $(document).off("click.waterwall","a[rel='collect']").on("click.waterwall","a[rel='collect']",function(e){
        		 var isResult=Ace.chkIsLogin(this,e);
	           if(isResult==false){
	           	  return false;
	          }
            var url=$(this).attr("data-collect-url");
            var $_self=$(this);
            if(collectFlag)
            {
            	collectFlag = false;
            	$.getJSON(url,function(data){
                    if(data.success){
                        //设值　
                        if(data.isCollect){
                            $_self.removeClass("a-collect").addClass("a-collect-current").find("span").text("已收藏");
                            $_self.attr("data-is-collect",true);
                            $_self.attr("data-collect-url",$_self.attr("data-collect-url").replace('/1/','/-1/'));
                        }else{
                            $_self.removeClass("a-collect-current").addClass("a-collect").find("span").text("收藏");
                            $_self.attr("data-is-collect",false);
                            $_self.attr("data-collect-url",$_self.attr("data-collect-url").replace('/-1/','/1/'));
                        }
                        collectFlag = true;
                    }
                });
            }
                
        });
        $(document).off("click.waterwall","a[rel='del']").on("click.waterwall", "a[rel='del']", function (e){

            var isResult = Ace.chkIsLogin(this, e);
            if(isResult == false)
            {
                return false;
            }
            
            var url = $(this).attr("data-del-url");
            var $_self = $(this);
            
            jConfirm("您确认要删除吗？", "温馨提示", function (r)
            {
                if(r)
                {
                    $.getJSON(url, function (data)
                    {
                        if(data.success)
                        {
                            // 结果校验
                            if(data.success != "" && data.success != "true")
                            {
                                return false;
                            }
                            else
                            {
                            	  jAlert("操作成功！", "温馨提示");
                            	  
                                // 删除成功则清除当前元素
                                $_self.closest(opts.itemSelector).remove();
                                $(opts.containor).masonry("reload");
                            }
                        }
                    });
                }
            });
        });
        
        var attentionFlag = true;
        $(document).off("click.waterwall","a[rel='attention']").on("click.waterwall","a[rel='attention']",function(e){
            var isResult=Ace.chkIsLogin(this,e);
	          if(isResult==false){
	           	  return false;
	          }
            var url=$(this).attr("data-attention-url");
            var $_self=$(this);
            if(attentionFlag)
            {
            	attentionFlag = false;
            	$.getJSON(url,function(data){
                    if(data.success){
                        //设值
                        if(data.isAttention){
                            $_self.text("取消关注");
                            $_self.attr("data-is-collect",true);
                            $_self.attr("data-attention-url",$_self.attr("data-attention-url").replace('/1/','/0/'));
                        }else{
                            $_self.text("关注");
                            $_self.attr("data-is-attention",false);
                            $_self.attr("data-attention-url",$_self.attr("data-attention-url").replace('/0/','/1/'));
                        }
                        attentionFlag = true;
                    }
                });
            }
                
        });
        //进行内容编辑时绑定事件
        $(document).off("mouseenter.waterwall").on("mouseenter.waterwall","a[rel='move']",function(e){
            var $_dropMenu=$(this).prev();
            var pos=$(this).position();
            pos._h=$(this).outerHeight();
            pos._w=$(this).outerWidth();
            $_dropMenu.css({
                display:"block",
                position:"absolute",
                width:pos._w-2,
                top:pos.top+pos._h-1,
                left:pos.left+4
            });
        }).off("mouseleave.waterwall").on("mouseleave.waterwall","a[rel='move']",function(e){
                var $_dropMenu=$(this).prev();
             var timer=window.setTimeout(function(){
                 $_dropMenu.hide();
             },100);
                $_dropMenu.on("mouseenter",function(){
                    window.clearTimeout(timer);
                    $_dropMenu.show();
                }).on("mouseleave",function(){
                    $_dropMenu.hide();
                });
         });
    },
    collect:function(){

    },
    oEvent:function(){
        var self=this;
        var opts=this.opts;
        self.support();
        self.collect();
        $(window).scrollTop(0);
        if(opts.firstQuery){
           self.getData();
        }
        //默认ok
        self.isFinish=true;
        $(window).on("smartscroll.waterwall",function(){
            var isReach=self.reachBottom();
            var isModalShow=$(".modal").is(":visible");
            if(isReach&&self.isFinish&&!isModalShow&&!opts.isOver){
              self.getData();
            }
        });
    },
    getData:function(){
        var opts=this.opts;
        var self=this;
        var $_containor=$(opts.containor);
        if(opts.autoAlign){
            //peter new add
            var $_pulls=$("[data-pull='true']");
            var currentH=$_containor.outerHeight();
            var hArray=[];
            $_pulls.each(function(index,item){
                var tempH=$(item).outerHeight();
                hArray.push(tempH);
            });
            var maxH= Math.max.apply(Math,hArray);
            var minH= Math.min.apply(Math,hArray);
            if((currentH-minH) > 500 && $_pulls.length>1){
                return false;
            }
        }
        
        var desturl=opts.path.join(opts.state.currNum);
        //默认使用json格式
        $.ajax({
            dataType: 'json',
            type: 'POST',
            data:{"isRand":opts.isRand, "maxArtId":opts.maxArtId },
            url: desturl,
            beforeSend:function(){
                self.isFinish=false;
                $("#J_loading_now").show();
            },
            success: function (data, textStatus, jqXHR) {
                $("#J_loading_now").fadeOut("fast");
                var tpl= self.getTpl(data);
                var $_containor=$(opts.containor);
                $(tpl).appendTo($_containor);
                $newElems=$_containor.find("[data-new=true]");
                $(opts.containor).masonry('appended', $newElems, false);
                $newElems.removeAttr("data-new").fadeIn();
                self.setMasonry();
                //flag标记为ready,并且让opts.state++;
                self.isFinish=true;
                if(opts.firstQuery){
                    $(window).scrollTop(0);
                    opts.firstQuery=false;
                }
                return;
            },
            error: function() {

            }
        });
    },
    reloadItem:function(){
        $(opts.containor).masonry("reload");
    },
    init:function(){
        var opts=this.opts;
        var that=this;
        this.oEvent();
    }
};